package com.hoperun.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.hoperun.bean.AdminManager;
import com.hoperun.bean.AdminPermissions;
import com.hoperun.bean.AdminRoles;
import com.hoperun.bean.query.QueryAdminManager;
import com.hoperun.dao.AdminPermissionsDAO;
import com.hoperun.dao.AdminRolesDAO;
import com.hoperun.framework.ibatis.page.BootGrid;
import com.hoperun.framework.ibatis.page.BootGridPage;
import com.hoperun.framework.query.Criteria;
import com.hoperun.framework.util.Constant;
import com.hoperun.service.IAdminRolesSV;
import com.hoperun.utils.LoginHelper;
import com.hoperun.utils.Constant.RecordState;


@Service("adminRolesSV")
public class AdminRolesSVImpl implements IAdminRolesSV
{     
	@Resource
	private AdminRolesDAO adminRolesDAO;
	@Resource
	private AdminPermissionsDAO adminPermissionsDAO;

	@Override
	public void delete(Long id) throws Exception
	{
		adminRolesDAO.delete(id);
	}

	@Override
	public AdminRoles queryById(Long id) throws Exception
	{
		return adminRolesDAO.queryById(id);
	}

	@Override
	public AdminRoles save(AdminRoles adminRoles) throws Exception
	{
		AdminManager adminManager = LoginHelper.getLoginUser();
		adminRoles.setCreator(adminManager.getManagerId());
		adminRoles.setCreatime(new Date());
		adminRoles.setStatus(RecordState.STS_USE);
		adminRoles.setVersion(Constant.ONE);
		adminRolesDAO.insert(adminRoles);
		return adminRoles;
	}

	@Override
	public void update(AdminRoles adminRoles) throws Exception
	{
		AdminManager adminManager = LoginHelper.getLoginUser();
		adminRoles.setUpdator(adminManager.getManagerId());
		adminRoles.setUpdatetime(new Date());
		adminRoles.setVersion(adminRoles.getVersion()+Constant.ONE);
		adminRolesDAO.update(adminRoles);
	}

	@Override
	public void saveOrUpdate(AdminRoles adminRoles)throws Exception
	{
		if(adminRoles == null)
            return;
		
		if(StringUtils.isNotBlank(""+ adminRoles.getRoleId()))
		{
			update(adminRoles);
		}
		else
		{
			save(adminRoles);
		}
	}

	@Override
	public void saveOrUpdate(List<AdminRoles> list)throws Exception
	{
		if(CollectionUtils.isNotEmpty(list))
		{
			for(AdminRoles adminRoles : list)
			{
				saveOrUpdate(adminRoles);
			}
		}
	}

	@Override
	public List<AdminRoles> queryByCondition(Criteria criteria)throws Exception
	{
		return adminRolesDAO.queryByCondition(criteria);
	}
	
	@Override
	public int queryCountByCondition(Criteria criteria)throws Exception
	{
		return adminRolesDAO.queryCountByCondition(criteria);
	}
	
	@Override
	public List<AdminPermissions> queryPermissByMgrId()throws Exception{
		AdminManager adminManager = LoginHelper.getLoginUser();
		List<AdminPermissions> adminPermissList = new ArrayList<AdminPermissions>();
		QueryAdminManager qa = new QueryAdminManager();
		qa.setManagerId(adminManager.getManagerId());
		AdminRoles ar = adminRolesDAO.queryByManagerId(qa);
		if(null != ar ){
			adminPermissList = queryPermissByRoles(ar);
		}
		return adminPermissList;
	}
	@Override
	public List<AdminPermissions> queryPermissByRoleId(Long roleId)throws Exception{
		List<AdminPermissions> adminPermissList = new ArrayList<AdminPermissions>();
		AdminRoles aRoles = queryById(roleId);
		adminPermissList = queryPermissByRoles(aRoles);
		return adminPermissList;
	}
	
	//根据角色信息查询对应的权限信息
	public List<AdminPermissions> queryPermissByRoles(AdminRoles aRoles)throws Exception{
		List<AdminPermissions> adminPermissList = new ArrayList<AdminPermissions>();
		if(StringUtils.isNotBlank(aRoles.getPermissions())){
			String[] permiss = aRoles.getPermissions().split(",");
			if(Constant.ZERO < permiss.length){
				Criteria criteria = new Criteria();
				for(int i = 0;i < permiss.length;i ++){
					if(i == 0){
						criteria.addEqual(AdminPermissions.COL_PERM_CODE, permiss[i], Criteria.AND);
					}else{
						criteria.addEqual(AdminPermissions.COL_PERM_CODE, permiss[i], Criteria.OR);
					}
				}
				criteria.addEqual(AdminPermissions.COL_STATUS, RecordState.STS_USE, Criteria.AND);
				adminPermissList = adminPermissionsDAO.queryByCondition(criteria);
				
			}
		}
		return adminPermissList;
	}
	
	@Override
	public BootGridPage<AdminRoles> queryPage(Criteria criteria,
			BootGrid<AdminRoles> grid) throws Exception 
	{

	//	AdminRoles model = grid.getEntity();

		int totalCount = adminRolesDAO.queryCountByCondition(criteria);

		if (Constant.ZERO < totalCount) {
			
			Map<String, String> sorts = grid.getSort();

			/** 设置排序规则 **/
			if (MapUtils.isNotEmpty(sorts)) {
				Set<String> keySets = sorts.keySet();
				String sort = "";
				for (String key : keySets) {
					sort += " , " + key + " " + sorts.get(key);
				}
				criteria.orderBy(sort.replaceFirst(",", ""));
			}
			if(grid.getCurrent() >= Constant.ZERO){
				int start = (grid.getCurrent() - Constant.ONE) * grid.getRowCount();
				int size = grid.getRowCount();
	
				criteria.limit(start, size);
			}
			List<AdminRoles> list = adminRolesDAO
					.queryByCondition(criteria);
			BootGridPage<AdminRoles> page = new BootGridPage<AdminRoles>(grid.getCurrent(), grid.getRowCount(), totalCount, list);

			return page;
		}
        return new BootGridPage<AdminRoles>(grid.getCurrent(), grid.getRowCount(), totalCount, new ArrayList<AdminRoles>());

	}

	@Override
	public void allocSave(String permission, Long[] ids) throws Exception {
		for(int i = 0;i < ids.length;i ++){
			AdminRoles ar = queryById(ids[i]);
			if(null != ar){
				ar.setPermissions(permission);
				update(ar);
			}
		}
	}

}
